package com.ucode.hrm.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.ucode.hrm.controller.service.ApiHrmDataPermissionService;
import com.ucode.hrm.controller.service.ApiHrmExcelHandleService;
import com.ucode.hrm.service.HrmCustomerCompanyService;
import com.ucode.hrm.service.HrmCustomerProjectService;
import com.ucode.model.hrm.HrmCustomerCompany;
import com.ucode.model.hrm.HrmCustomerProject;
import com.ucode.model.hrm.convert.HrmCustomerProjectConvert;
import com.ucode.model.hrm.form.HrmCustomerProjectForm;
import com.ucode.model.hrm.vo.HrmCustomerProjectVO;
import com.ucode.model.sys.user.AdminUser;
import com.ucode.ssm.busiconf.service.SysConfigService;
import com.ucode.ssm.user.service.AdminUserService;
import com.ucode.tool.annotation.DataPermission;
import com.ucode.tool.base.Paginator;
import com.ucode.tool.base.ResponseResult;
import com.ucode.tool.base.enums.CommonSwitchStatusEnum;
import com.ucode.tool.util.CollectionUtils;
import com.ucode.tool.util.IdentifyUtils;
import com.ucode.tool.validator.InEnum;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Tag(name = "管理后台 - 人力资源系统 - 客户项目")
@RestController
@RequestMapping("/hrm/customer-project")
@Validated
public class HrmCustomerProjectController {
    private static final Log log = LogFactory.get();

    @Resource
    private HrmCustomerProjectService customerProjectService;
    @Resource
    private HrmCustomerCompanyService  customerCompanyService;
    @Resource
    private AdminUserService adminUserService;
    @Resource
    private ApiHrmDataPermissionService apiHrmDataPermissionService ;
    @Resource
    private ApiHrmExcelHandleService apiHrmExcelHandleService;
    @Resource
    private SysConfigService sysConfigService;

    // 到期提醒时间
    private static final String hrm_ec_customer_project_time = "hrm_ec_customer_project_time";

    @GetMapping("/page-list")
    @Operation(summary = "获得分页列表")
    @PreAuthorize("@usfs.hasPermission('hrm:customer-project:query')")
    @DataPermission(permissions={"hrm:customer-project:query"})
    public ResponseResult<Paginator<HrmCustomerProjectVO>> pageList(
            @Schema(description = "客户公司编码") @RequestParam(value = "customerCompanyId",required = false) Long customerCompanyId,
            @Schema(description = "项目名称") @RequestParam(value = "projectName",required = false) String projectName,
            @Schema(description = "项目经理") @RequestParam(value = "projectManager",required = false) String projectManager,
            @Schema(description = "项目经理手机号") @RequestParam(value = "mobile",required = false) String mobile,
            @Schema(description = "项目状态") @RequestParam(value = "status",required = false) Integer status,
            @Schema(description = "负责人") @RequestParam(value = "ownerAdminId",required = false) Long ownerAdminId,
            @Schema(description = "创建时间区间",example = "[2022-07-01 00:00:00,2022-07-01 23:59:59]")  @RequestParam(value = "createTimeInterval",required = false) LocalDateTime[] createTimeInterval,
            @Schema(description = "页码",example="1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @Schema(description = "每页记录数",example="5") @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize){

        Map<String,Object> condition = new HashMap<>();
        if(StrUtil.isNotBlank(projectName))
            condition.put("projectName", StrUtil.concat(true,"%", projectName,"%"));
        if(StrUtil.isNotBlank(mobile))
            condition.put("mobile", StrUtil.concat(true,"%", mobile,"%"));
        if(StrUtil.isNotBlank(projectManager))
            condition.put("projectManager", StrUtil.concat(true,"%", projectManager,"%"));
        if(ArrayUtil.isNotEmpty(createTimeInterval) && createTimeInterval.length == 2){
            condition.put("startTime",createTimeInterval[0]);
            condition.put("endTime",createTimeInterval[1]);
        }
        condition.put("customerCompanyId",customerCompanyId);
        condition.put("dataUserIds",apiHrmDataPermissionService.getCurrentUserByDataPermission());
        condition.put("status",status);
        condition.put("deltag",false);
        condition.put("ownerAdminId",ownerAdminId);

        return ResponseResult.success(pageList(condition,pageNum,pageSize));
    }

    @GetMapping("/ec-page-list")
    @Operation(summary = "获得期满客户项目分页列表")
    @PreAuthorize("@usfs.hasPermission('hrm:ec-customer-project:query')")
    @DataPermission(permissions={"hrm:ec-customer-project:query"})
    public ResponseResult<Paginator<HrmCustomerProjectVO>> pageListByEc(
            @Schema(description = "场景类型:1、即将到期或已到期项目 2、即将到期项目 3、已到期项目") @RequestParam(value = "sceneType",required = true) Integer sceneType,
            @Schema(description = "客户公司编码") @RequestParam(value = "customerCompanyId",required = false) Long customerCompanyId,
            @Schema(description = "项目名称") @RequestParam(value = "projectName",required = false) String projectName,
            @Schema(description = "项目经理") @RequestParam(value = "projectManager",required = false) String projectManager,
            @Schema(description = "项目经理手机号") @RequestParam(value = "mobile",required = false) String mobile,
            @Schema(description = "项目状态") @RequestParam(value = "status",required = false) Integer status,
            @Schema(description = "负责人") @RequestParam(value = "ownerAdminId",required = false) Long ownerAdminId,
            @Schema(description = "创建时间区间",example = "[2022-07-01 00:00:00,2022-07-01 23:59:59]")  @RequestParam(value = "createTimeInterval",required = false) LocalDateTime[] createTimeInterval,
            @Schema(description = "页码",example="1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @Schema(description = "每页记录数",example="5") @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize){

        Map<String,Object> condition = new HashMap<>();
        if(StrUtil.isNotBlank(projectName))
            condition.put("projectName", StrUtil.concat(true,"%", projectName,"%"));
        if(StrUtil.isNotBlank(mobile))
            condition.put("mobile", StrUtil.concat(true,"%", mobile,"%"));
        if(StrUtil.isNotBlank(projectManager))
            condition.put("projectManager", StrUtil.concat(true,"%", projectManager,"%"));
        if(ArrayUtil.isNotEmpty(createTimeInterval) && createTimeInterval.length == 2){
            condition.put("startTime",createTimeInterval[0]);
            condition.put("endTime",createTimeInterval[1]);
        }
        condition.put("customerCompanyId",customerCompanyId);
        condition.put("dataUserIds",apiHrmDataPermissionService.getCurrentUserByDataPermission());
        condition.put("status",status);
        condition.put("deltag",false);
        condition.put("ownerAdminId",ownerAdminId);

        condition.put("sceneType",sceneType);
        if(ObjUtil.equals(sceneType,1) || ObjUtil.equals(sceneType,2)){
            String reminderTimeStr = sysConfigService.getPropertyValue(hrm_ec_customer_project_time);
            Integer reminderTime = StrUtil.isBlank(reminderTimeStr) ? 10 : Integer.parseInt(reminderTimeStr);
            condition.put("ecTime",LocalDateTime.now().plusDays(reminderTime));//提前提醒时间
            condition.put("currentDate",LocalDateTime.now());
        }else {
            condition.put("currentDate",LocalDateTime.now());
        }
        return ResponseResult.success(pageList(condition,pageNum,pageSize));
    }

    @GetMapping("/list-simple-page")
    @Operation(summary = "分页获取精简信息列表(没有权限校验，公共查询接口)", description = "主要用于前端的下拉选项")
    @DataPermission(permissions={"hrm:customer-project:query"})
    public ResponseResult<Paginator<HrmCustomerProjectVO>> simplePageList(
                                                                        @Schema(description = "关键字")  @RequestParam(value = "keyword",required = false) String keyword,
                                                                        @Schema(description = "页码",example="1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                                        @Schema(description = "每页记录数",example="5") @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {
        Map<String,Object> condition = new HashMap<>();
        if(StrUtil.isNotBlank(keyword))
            condition.put("projectName", StrUtil.concat(true,"%", keyword,"%"));
        condition.put("deltag",false);
        condition.put("dataUserIds",apiHrmDataPermissionService.getCurrentUserByDataPermission());

        return ResponseResult.success(pageList(condition,pageNum,pageSize));
    }

    private Paginator<HrmCustomerProjectVO> pageList(Map<String,Object> condition, int pageNum, int pageSize) {
        Paginator<HrmCustomerProject> paginator = customerProjectService.queryPageForList(condition,pageSize,pageNum);
        Paginator<HrmCustomerProjectVO> paginatorVO =  HrmCustomerProjectConvert.INSTANCE.convertPage(paginator);

        if(CollUtil.isNotEmpty(paginatorVO.getList())) {
            Set<Long> customerCompanyIds =   CollectionUtils.convertSet( paginatorVO.getList(),HrmCustomerProjectVO::getCustomerCompanyId);
            Set<Long> adminIds =   CollectionUtils.convertSet( paginatorVO.getList(),HrmCustomerProjectVO::getOwnerAdminId);
            Map<Long, AdminUser> adminUserMap = adminUserService.getUserMap(adminIds);
            Map<Long, HrmCustomerCompany> customerCompanyMap = customerCompanyService.getMap(customerCompanyIds);
            paginatorVO.getList().forEach(item -> {
                HrmCustomerCompany customerCompany = customerCompanyMap.get(item.getCustomerCompanyId());
                if(customerCompany != null)
                    item.setCompanyName(customerCompany.getCompanyName());
                AdminUser adminUser = adminUserMap.get(item.getOwnerAdminId());
                if(adminUser != null)
                    item.setOwnerAdminName(adminUser.getNickname());
            });
        }

        return paginatorVO;
    }

    @GetMapping("/getById/{id}")
    @Parameter(description="主键ID",name = "id", required = true,in = ParameterIn.PATH,example = "1024")
    @Operation(summary = "主键获得信息")
    @PreAuthorize("@usfs.hasPermission('hrm:customer-project:query')")
    public ResponseResult<HrmCustomerProjectVO> getById(@PathVariable(name="id",required=true) Long id){
        HrmCustomerProject bean = customerProjectService.validate(id);
        HrmCustomerProjectVO vo = HrmCustomerProjectConvert.INSTANCE.convert(bean);
        HrmCustomerCompany customerCompany = customerCompanyService.selectByPrimaryKey(bean.getCustomerCompanyId());
        if(customerCompany != null)
            vo.setCompanyName(customerCompany.getCompanyName());

        AdminUser adminUser = adminUserService.selectByPrimaryKey(vo.getOwnerAdminId());
        if(adminUser != null)
            vo.setOwnerAdminName(adminUser.getNickname());

        return ResponseResult.success(vo);
    }

    @PostMapping("/create")
    @Operation(summary = "创建")
    @PreAuthorize("@usfs.hasPermission('hrm:customer-project:create')")
    public ResponseResult<Long> create(@Valid @RequestBody HrmCustomerProjectForm form) {
        HrmCustomerProject bean = HrmCustomerProjectConvert.INSTANCE.convert(form);
        bean.setId(IdentifyUtils.getDefaultSnowflakeId());
        Long id = customerProjectService.insert(bean);
        return id != null ? ResponseResult.success(id) : ResponseResult.failed();
    }

    @PostMapping("/update/{id}")
    @Parameter(description="主键ID",name = "id", required = true,in = ParameterIn.PATH,example = "1024")
    @Operation(summary = "修改")
    @PreAuthorize("@usfs.hasPermission('hrm:customer-project:update')")
    public ResponseResult<Object> update(@PathVariable(name="id",required=true) Long id,
                                         @Valid @RequestBody HrmCustomerProjectForm form) {
        HrmCustomerProject bean = HrmCustomerProjectConvert.INSTANCE.convert(form);
        bean.setId(id);
        int i = customerProjectService.update(bean);
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }

    @PostMapping("/update-status")
    @Operation(summary = "修改状态")
    @PreAuthorize("@usfs.hasPermission('hrm:customer-project:update')")
    public ResponseResult<Boolean> updateStatus(@Schema(description = "编号集合",requiredMode = Schema.RequiredMode.REQUIRED)
                                                @NotEmpty(message = "编号集合为空")@Size(min = 1,max = 100,message = "编号集合数量为1-100条")
                                                @RequestParam(value = "ids",required = true) List<Long> ids,
                                                @Schema(description = "状态",requiredMode = Schema.RequiredMode.REQUIRED,allowableValues = {"0","1"})
                                                @InEnum(value = CommonSwitchStatusEnum.class, message = "修改的状态值必须是 {value}")
                                                @RequestParam(value = "status",required = true) Integer status) {
        int i = customerProjectService.updateStatus(ids, status);
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }


    @PostMapping("/logic-delete/{id}")
    @Operation(summary = "转移到回收站")
    @Parameter(description="主键ID",name = "id", required = true,in = ParameterIn.PATH, example = "1024")
    @PreAuthorize("@usfs.hasPermission('hrm:customer-project:logic-delete')")
    public ResponseResult<Object> logicDelete(@PathVariable(name="id",required=true) Long id) {
        //逻辑删除
        int i = customerProjectService.logicDeletePrimaryKey(id);
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }

    @PostMapping("/batch-logic-delete")
    @Operation(summary = "批量转移到回收站")
    @PreAuthorize("@usfs.hasPermission('hrm:customer-project:logic-delete')")
    public ResponseResult<Boolean> batchLogicDeletePrimaryKey(@Schema(description = "编号集合",requiredMode = Schema.RequiredMode.REQUIRED)
                                                @NotEmpty(message = "编号集合为空")@Size(min = 1,max = 100,message = "编号集合数量为1-100条")
                                                @RequestParam(value = "ids",required = true) List<Long> ids) {
        int i = customerProjectService.logicDeleteByPrimaryKeys(ids);
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }

    @PostMapping("/import") // 映射到/api/excel/parse
    @Operation(summary = "导入")
    @PreAuthorize("@usfs.hasPermission('hrm:customer-project:create')")
    public ResponseResult<Boolean> importEmployeesData(@RequestParam("file") MultipartFile file) throws IOException {

        new Thread(() -> {
            try {
                apiHrmExcelHandleService.importCustomerContactsData(file);
            } catch (Exception e) {
                log.error("导入客户项目异常了...",e);
            }
        }).start();
        return ResponseResult.success();
    }

}
